/* eslint-disable jsdoc/check-tag-names */
'use strict';

const Controller = require('./base');
const { Op } = require('sequelize');
/**
 * @Controller cw_dev 开发设置
 */
class CwDevController extends Controller {

  /**
   * @summary 获取系统菜单
   * @description 获取系统菜单
   * @router get /adminApi/cw_dev/getMenu
   * @request header string token 用户token
   * @response 200 baseResponse 菜单信息
   */
  async getMenu() {
    const { ctx } = this;
    const { cw } = ctx.helper;
    const map = {};
    map.order = [[ 'sort', 'ASC' ]];
    map.where = {};
    map.where.mod_id = 1;
    map.where.admin = false;
    const roleIds = await ctx.service.cwRbac.getRoleIds(ctx.userInfo.id);
    if (!cw._.isEmpty(roleIds)) {
      map.where.id = { [Op.in]: roleIds };
    }
    const list = await ctx.model.CwMenu.findAll(map);
    const tree = cw.arr_to_tree(list, 0, true);
    // console.log(JSON.stringify(tree, null, 2));
    this.success(tree);
  }
  /**
  * @summary 获取中间件
  * @description 获取项目中自定义的中间件
  * @router get /adminApi/cw_dev/getMiddleware
  * @request header string token 用户token
  * @response 200 menuResponse tree
  */
  async getMiddleware() {
    const data = await this.ctx.service.cwMiddleware.getList();
    this.success(data);
  }
  /**
  * @summary 添加模块
  * @description 添加模块
  * @router post /adminApi/cw_dev/addMod
  * @request header string token 用户token
  * @request body modRequest *body 不提交id字段
  * @response 200 baseResponse errorCode=0添加成功
  */
  async addMod() {
    const data = this.ctx.request.body;
    if (!this.ctx.helper.cw._.isEmpty(data.middleware)) {
      data.middleware = data.middleware.join(',');
    } else {
      data.middleware = '';
    }
    // console.log(data);
    const add = await this.ctx.model.CwMenuMod.create(data);
    this.success(add);
  }
  /**
  * @summary 编辑模块
  * @description 编辑模块
  * @router post /adminApi/cw_dev/editMod
  * @request header string token 用户token
  * @request body modRequest *body 提交id字段
  * @response 200 baseResponse errorCode=0编辑成功
  */
  async editMod() {
    const data = this.ctx.request.body;
    if (!this.ctx.helper.cw._.isEmpty(data.middleware)) {
      data.middleware = data.middleware.join(',');
    } else {
      data.middleware = '';
    }
    const up = await this.ctx.model.CwMenuMod.update(data, {
      where: { id: data.id },
    });
    // console.log(data);
    this.success(up);
  }
  /**
  * @summary 删除模块
  * @description 删除模块
  * @router get /adminApi/cw_dev/delMod
  * @request header string token 用户token
  * @request query integer *id 模块id
  * @response 200 baseResponse errorCode=0成功
  */
  async delMod() {
    const id = this.ctx.query.id;
    const del = await this.ctx.model.CwMenuMod.destroy({ where: { id } });
    await this.ctx.model.CwMenu.destroy({ where: { mod_id: id } });
    this.success(del);
  }
  /**
  * @summary 获取模块详情
  * @description 获取模块详情
  * @router get /adminApi/cw_dev/getModInfo
  * @request header string token 用户token
  * @request query integer *id 模块id
  * @response 200 modeInfoResponse errorCode=0成功
  */
  async getModInfo() {
    const id = this.ctx.query.id;
    const map = {};
    map.where = {};
    if (!this.ctx.helper.cw._.isEmpty(id)) {
      map.where.id = id;
    } else {
      map.where.sys = 1;
    }
    const info = await this.ctx.model.CwMenuMod.findOne(map);
    if (info) {
      // console.log(info);
      info.dataValues.middlewareArr = !this.ctx.helper.cw._.isEmpty(
        info.middleware
      )
        ? info.middleware.split(',')
        : [];
    }
    this.success(info);
  }
  /**
  * @summary 获取模块列表
  * @description 获取模块列表
  * @router get /adminApi/cw_dev/getModList
  * @request header string token 用户token
  * @response 200 modeListResponse desc
  */
  async getModList() {
    const map = {};
    map.order = [
      [ 'sys', 'DESC' ],
      [ 'sort', 'ASC' ],
    ];
    map.attributes = [
      [ 'id', 'key' ],
      [ 'name', 'label' ],
    ];
    const list = await this.ctx.model.CwMenuMod.findAll(map);
    this.success(list);
  }
  /**
  * @summary 获取路由列表
  * @description 获取路由列表
  * @router get /adminApi/cw_dev/getTreeMenu
  * @request header string token 用户token
  * @request query integer mod_id 模块id
  * @request query boolean admin 是否后端
  * @request query string name 路由名称
  * @request query string path 路由url
  * @request query string controller 控制器
  * @request query string action 控制器
  * @request query string verb 请求方式
  * @request query string middleware 中间件
  * @request query string ignoreMiddleware 排除中间件
  * @request query string parentKeys 当此节点被选中的时候也会选中 parentKeys 的节点
  * @request query string access 权限配置，需要预先配置权限
  * @response 200 menuResponse desc
  */
  async getTreeMenu() {
    const { ctx } = this;
    const {
      mod_id,
      admin,
      name,
      path,
      controller,
      action,
      verb,
      middleware,
      ignoreMiddleware,
      parentKeys,
      access,
    } = ctx.query;
    const { cw } = ctx.helper;
    const map = {};
    map.order = [[ 'sort', 'ASC' ]];
    map.where = {};
    map.where.mod_id = mod_id;
    if (!cw._.isEmpty(admin) && admin !== 'all') {
      map.where.admin = admin === 'true';
    }
    if (!cw._.isEmpty(name)) {
      map.where.name = { [Op.like]: `%${name}%` };
    }
    if (!cw._.isEmpty(path)) {
      map.where.path = { [Op.like]: `%${path}%` };
    }
    if (!cw._.isEmpty(controller)) {
      map.where.controller = { [Op.like]: `%${controller}%` };
    }
    if (!cw._.isEmpty(action)) {
      map.where.action = { [Op.like]: `%${action}%` };
    }
    if (!cw._.isEmpty(middleware)) {
      map.where.middleware = { [Op.like]: `%${middleware}%` };
    }
    if (!cw._.isEmpty(ignoreMiddleware)) {
      map.where.ignoreMiddleware = { [Op.like]: `%${ignoreMiddleware}%` };
    }
    if (!cw._.isEmpty(parentKeys)) {
      map.where.parentKeys = { [Op.like]: `%${parentKeys}%` };
    }
    if (!cw._.isEmpty(access)) {
      map.where.access = { [Op.like]: `%${access}%` };
    }
    if (!cw._.isEmpty(verb) && verb !== 'all') {
      map.where.verb = { [Op.like]: `%${verb}%` };
    }
    const list = await ctx.model.CwMenu.findAll(map);
    let tree;
    if (
      (!cw._.isEmpty(admin) && admin !== 'all') ||
      !cw._.isEmpty(name) ||
      !cw._.isEmpty(path) ||
      !cw._.isEmpty(controller) ||
      !cw._.isEmpty(action) ||
      (!cw._.isEmpty(verb) && verb !== 'all') ||
      !cw._.isEmpty(middleware) ||
      !cw._.isEmpty(ignoreMiddleware) ||
      !cw._.isEmpty(parentKeys) ||
      !cw._.isEmpty(access)
    ) {
      tree = list;
    } else {
      tree = cw.arr_to_tree(list, 0);
    }
    this.success(tree);
  }
  /**
  * @summary 添加路由
  * @description 添加路由
  * @router post /adminApi/cw_dev/addRouter
  * @request header string token 用户token
  * @request body menuItem *body 不提交id
  * @response 200 baseResponse errorCode:0添加成功
  */
  async addRouter() {
    const { ctx } = this;
    const { cw } = ctx.helper;
    const data = ctx.request.body;
    // console.log(data);
    data.parentKeys = !cw._.isEmpty(data.parentKeys)
      ? data.parentKeys.join(',')
      : '';
    data.access = !cw._.isEmpty(data.access) ? data.access.join(',') : '';
    data.middleware = !cw._.isEmpty(data.middleware)
      ? data.middleware.join(',')
      : '';
    data.ignoreMiddleware = !cw._.isEmpty(data.ignoreMiddleware)
      ? data.ignoreMiddleware.join(',')
      : '';
    data.controller = !cw._.isEmpty(data.controller) ? data.controller : '';
    data.action = !cw._.isEmpty(data.action) ? data.action : '';
    // console.log(data);
    const add = await this.ctx.model.CwMenu.create(data);
    await ctx.service.cwGenerateRoute.run();
    this.success(add);
  }
  /**
  * @summary 编辑路由
  * @description 编辑路由
  * @router post /adminApi/cw_dev/editRouter
  * @request header string token 用户token
  * @request body menuItem *body 提交id
  * @response 200 baseResponse errorCode:0添加成功
  */
  async editRouter() {
    const { ctx } = this;
    const { cw } = ctx.helper;
    const data = ctx.request.body;
    data.parentKeys = !cw._.isEmpty(data.parentKeys)
      ? data.parentKeys.join(',')
      : '';
    data.access = !cw._.isEmpty(data.access) ? data.access.join(',') : '';
    data.middleware = !cw._.isEmpty(data.middleware)
      ? data.middleware.join(',')
      : '';
    data.ignoreMiddleware = !cw._.isEmpty(data.ignoreMiddleware)
      ? data.ignoreMiddleware.join(',')
      : '';
    data.controller = !cw._.isEmpty(data.controller) ? data.controller : '';
    data.action = !cw._.isEmpty(data.action) ? data.action : '';
    data.verb = !cw._.isEmpty(data.verb) ? data.verb : 'get';
    data.icon = !cw._.isEmpty(data.icon) ? data.icon : '';
    // console.log(data);
    const up = await this.ctx.model.CwMenu.update(data, {
      where: { id: data.id },
    });
    await ctx.service.cwGenerateRoute.run();
    this.success(up);
  }
  /**
  * @summary 删除路由
  * @description 删除路由
  * @router get /adminApi/cw_dev/delRouter
  * @request header string token 用户token
  * @request query integer *id 路由id
  * @response 200 baseResponse errorCode:0成功
  */
  async delRouter() {
    const id = this.ctx.query.id;
    const del = await this.ctx.model.CwMenu.destroy({ where: { id } });
    await this.ctx.model.CwMenu.destroy({ where: { pid: id } });
    await this.ctx.service.cwGenerateRoute.run();
    this.success(del);
  }
  /**
  * @summary 获取控制器列表
  * @description 获取控制器列表
  * @router get /adminApi/cw_dev/getController
  * @request header string token 用户token
  * @response 200 baseResponse errorCode:0成功
  */
  async getController() {
    const data = await this.ctx.service.cwController.getList();
    this.success(data);
  }
  /**
  * @summary 获取控制器方法
  * @description 获取控制器方法
  * @router get /adminApi/cw_dev/getControllerFun
  * @request header string token 用户token
  * @request query integer *c 控制器名称
  * @response 200 baseResponse errorCode:0成功
  */
  async getControllerFun() {
    const { c } = this.ctx.query;
    const data = await this.ctx.service.cwController.getFun(c);
    this.success(data);
  }
  /**
  * @summary 获取全部树路由节点
  * @description 获取全部树路由节点
  * @router get /adminApi/cw_dev/getAllTreeMenu
  * @request header string token 用户token
  * @request query integer *mod_id 模块id
  * @response 200 baseResponse errorCode:0成功
  */
  async getAllTreeMenu() {
    const { ctx } = this;
    const { mod_id } = ctx.query;
    const { cw } = ctx.helper;
    const map = {};
    map.order = [[ 'sort', 'ASC' ]];
    map.where = {};
    map.where.mod_id = mod_id;
    map.attributes = { exclude: [ 'role' ] };
    const list = await ctx.model.CwMenu.findAll(map);
    const tree = cw.arr_to_tree(list, 0);
    this.success([{ name: '一级路由', id: 0 }, ...tree ]);
  }
}

module.exports = CwDevController;
